<template>
  <div class="select">
    <van-field
      class="iptBox"
      is-link
      :readonly="true"
      clickable
      :required="required"
      :name="name"
      @focus="selectArea"
      v-model="areaFullName"
      :label="label"
      placeholder="请选择"
      :rules="[{ required: required }]"
    />
    <van-popup
      round
      v-model:show="showAddressSelector"
      @close="closeAreaPop"
      position="bottom"
      :style="{ height: '70%' }"
    >
      <!-- 选择器主体 -->
      <div class="page-main">
        <!-- 操作区域 包含取消和确定 -->
        <div class="main-operate">
          <div class="title-txt" @click.stop="handleCancel">取消</div>
          <div class="title-txt" @click.stop="handleSubmit">确定</div>
        </div>
        <!-- 已选择的地址信息 -->
        <div
          class="main-select"
          :class="[selectAreaLevelLimit == 3 ? 'w33_percent' : '']"
        >
          <div
            v-if="showIndex == 0 || state.provinceObj.name"
            :class="showIndex == 0 ? 'select' : ''"
            @click="anewSelect(0)"
          >
            {{ state.provinceObj.name || '请选择' }}
          </div>
          <div
            v-if="showIndex == 1 || state.cityObj.name"
            :class="showIndex == 1 ? 'select' : ''"
            @click="anewSelect(1)"
          >
            {{ state.cityObj.name || '请选择' }}
          </div>
          <div
            v-if="showIndex == 2 || state.areaObj.name"
            :class="showIndex == 2 ? 'select' : ''"
            @click="anewSelect(2)"
          >
            {{ state.areaObj.name || '请选择' }}
          </div>
          <div
            v-if="showIndex == 3 || state.streetObj.name"
            :class="showIndex == 3 ? 'select' : ''"
            @click="anewSelect(3)"
          >
            {{ state.streetObj.name || '请选择' }}
          </div>
          <div
            v-if="showIndex == 4 || state.villageObj.name"
            :class="showIndex == 4 ? 'select' : ''"
            @click="anewSelect(4)"
          >
            {{ state.villageObj.name || '请选择' }}
          </div>
        </div>
        <!-- 待选择的地址信息 -->
        <div class="main-list">
          <van-loading
            style="
              position: absolute;
              left: 50%;
              top: 50%;
              transform: translate(-50%, -50%);
            "
            v-if="isLoading"
          />
          <div v-if="showIndex == 0">
            <div
              class="list-box"
              :class="state.provinceObj.id == item.id ? 'active' : ''"
              @click="handleSelectAddress(0, item)"
              v-for="item in state.provinceData"
              :key="item.id"
            >
              <div>{{ item.name || '' }}</div>
            </div>
          </div>
          <div v-if="showIndex == 1">
            <div
              class="list-box"
              :class="state.cityObj.id == item.id ? 'active' : ''"
              @click="handleSelectAddress(1, item)"
              v-for="item in state.cityData"
              :key="item.id"
            >
              <div>{{ item.name || '' }}</div>
            </div>
          </div>
          <div v-if="showIndex == 2">
            <div
              class="list-box"
              :class="state.areaObj.id == item.id ? 'active' : ''"
              @click="handleSelectAddress(2, item)"
              v-for="item in state.areaData"
              :key="item.id"
            >
              <div>{{ item.name || '' }}</div>
            </div>
          </div>
          <div v-if="showIndex == 3">
            <div
              class="list-box"
              :class="state.streetObj.id == item.id ? 'active' : ''"
              @click="handleSelectAddress(3, item)"
              v-for="item in state.streetsData"
              :key="item.id"
            >
              <div>{{ item.name || '' }}</div>
            </div>
          </div>
          <div v-if="showIndex == 4">
            <div
              class="list-box"
              :class="state.villageObj.id == item.id ? 'active' : ''"
              @click="handleSelectAddress(4, item)"
              v-for="item in state.villagesData"
              :key="item.id"
            >
              <div>{{ item.name || '' }}</div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
// 自定义区划选择器-可限制选择层级、默认选择层级、回显地址
import { gerAreaByCode } from '@/api/api.js'
import { reactive, ref } from '@vue/reactivity'
import { watch } from 'vue'
import { onBeforeMount } from '@vue/runtime-core'
import { showSuccessToast, showFailToast } from 'vant'
const props = defineProps({
  // 组件树回显地址对象
  areaInfoSelected: {
    type: Object,
    default: {}
  },
  // 传0-5  0 可选任意一级 1省级 2市级 3县区级 4街道/乡镇 5社区/村
  selectAreaLevelLimit: {
    type: Number,
    default: 5
  },
  // field文本框回显值-显示在外层
  // value: {
  //   type: [String, Number],
  //   require: false
  // },
  // label标题
  label: {
    type: String,
    require: false
  },
  // 绑定标识
  name: {
    type: String,
    require: false
  },
  // 是否必填
  required: {
    type: Boolean,
    require: false,
    default: false
  },
  // true户籍地址 false常住地址
  isRegister: {
    type: Boolean,
    require: false,
    default: false
  },
  // 是否只读
  readonly: {
    type: Boolean,
    require: false,
    default: false
  },
  // 限制默认最小回显等级 0省级 1市级 2县区级 ；必须设置默认组件树回显地址对象areaInfoSelected或者isXiaMen
  defaultLimitArea: {
    type: Number,
    require: false,
    default: -1
  },
  // 回显数据时是否展示到回显地址的下一级(如true：需要回显的区划为：安徽省合肥市，则区划选择器中默认展示到区县一列)
  isCurrentLevelDisable: {
    type: Boolean,
    require: false,
    default: true
  }
  // defaultLimitArea   areaInfoSelected      level
  // 		0		      传值需默认到区级         2
  // 		1		      传值需默认到区级         3
  // 		2		      传值需默认到乡镇街道级    4
  // 		3		      传值需默认到社区村级      5
  // 是否默认从厦门开始选择
  // isXiaMen: {
  //   type: Boolean,
  //   require: false,
  //   default: false,
  // },
})

const currentLastLevel = ref(0) // 当前接口拿到的最后一级行政级别
const showAddressSelector = ref(false)
const isLoading = ref(false)
const areaFullName = ref('')
const showIndex = ref(0) // 地区显示
const state = reactive({
  provinceObj: {},
  cityObj: {},
  areaObj: {},
  streetObj: {},
  villageObj: {},
  provinceData: [], // 省级
  cityData: [], // 市级
  areaData: [], //县区
  streetsData: [], //街道
  villagesData: [] // 村、社区
})
const emit = defineEmits(['confirm', 'update:value'])

watch(
  () => showAddressSelector.value,
  val => {
    if (val) {
      getDefaultArea()
    }
  }
)

onBeforeMount(() => {
  getDefaultArea()
})

const selectArea = () => {
  if (!props.readonly) {
    showAddressSelector.value = true
  }
}
const getDefaultArea = () => {
  if (
    props.areaInfoSelected &&
    props.areaInfoSelected.provinceObj &&
    props.areaInfoSelected.provinceObj.id
  ) {
    let { provinceObj, cityObj, areaObj, streetObj, villageObj } =
      props.areaInfoSelected
    state.provinceObj = provinceObj
    state.cityObj = cityObj
    state.areaObj = areaObj
    state.streetObj = streetObj
    state.villageObj = villageObj
    if (!cityObj.id) {
      handleGetMap({}, 'init')
    }
    if (cityObj.id && !areaObj.id) {
      if (props.isCurrentLevelDisable) {
        handleGetMap(props.areaInfoSelected.cityObj, 'city')
      } else {
        handleGetMap(props.areaInfoSelected.provinceObj, 'pro')
      }
    }
    if (areaObj.id && !streetObj.id) {
      if (props.isCurrentLevelDisable) {
        handleGetMap(props.areaInfoSelected.areaObj, 'area')
      } else {
        handleGetMap(props.areaInfoSelected.cityObj, 'city')
      }
    }
    if (streetObj.id && !villageObj.id) {
      if (isCurrentLevelDisable) {
        handleGetMap(props.areaInfoSelected.streetObj, 'street')
      } else {
        handleGetMap(props.areaInfoSelected.areaObj, 'area')
      }
    }

    handleGetMap(props.areaInfoSelected.streetObj, 'street')
    // 填充输入框地址全称
    areaFullName.value =
      props.areaInfoSelected.provinceObj.name +
      props.areaInfoSelected.cityObj.name +
      props.areaInfoSelected.areaObj.name +
      props.areaInfoSelected.streetObj.name +
      props.areaInfoSelected.villageObj.name
  } else {
    handleGetMap({}, 'init')
  }
}
const closeAreaPop = () => {
  // emit("update:showAddressSelector", false);
  showAddressSelector.value = false
}
//取消
const handleCancel = () => {
  // emit("cancel");
  showAddressSelector.value = false
}
//确定
const handleSubmit = () => {
  const { provinceObj, cityObj, areaObj, streetObj, villageObj } = state
  const arr = [provinceObj, cityObj, areaObj, streetObj, villageObj]
  let fullAreaName = []
  arr.map(item => {
    if (item.id) {
      fullAreaName.push(item.name)
    }
  })
  if (props.selectAreaLevelLimit && props.selectAreaLevelLimit != 0) {
    if (props.selectAreaLevelLimit > 0) {
      if (fullAreaName.length < props.selectAreaLevelLimit) {
        if (props.selectAreaLevelLimit == 2) {
          showFailToast('地址需精确到市级')
        }
        if (props.selectAreaLevelLimit == 3) {
          showFailToast('地址需精确到县区级')
        }
        if (props.selectAreaLevelLimit == 4) {
          showFailToast('地址需精确到街道/乡镇级')
        }
        if (props.selectAreaLevelLimit == 5) {
          showFailToast('地址需精确到社区/村级')
        }
        return
      }
    } else {
      // 限制必须选择到最后一级
      console.log(fullAreaName.length)
      if (currentLastLevel.value != fullAreaName.length) {
        showFailToast('地址需精确最后一级')
        return
      }
    }
  }
  let areaInfoObj
  if (props.isRegister) {
    areaInfoObj = {
      obj: {
        registerProvince: provinceObj.id || '',
        registerCity: cityObj.id || '',
        registerCounty: areaObj.id || '',
        registerStreet: streetObj.id || '',
        registerCommunity: villageObj.id || '',
        registerProvinceName: provinceObj.name || '',
        registerCityName: cityObj.name || '',
        registerCountyName: areaObj.name || '',
        registerStreetName: streetObj.name || '',
        registerCommunityName: villageObj.name || ''
      },
      defaultObj: {
        provinceObj,
        cityObj,
        areaObj,
        streetObj,
        villageObj
      },
      fullArea: fullAreaName.toString().replace(/,/g, '')
    }
  } else {
    areaInfoObj = {
      obj: {
        province: provinceObj.id || '',
        city: cityObj.id || '',
        county: areaObj.id || '',
        street: streetObj.id || '',
        community: villageObj.id || '',
        provinceName: provinceObj.name || '',
        cityName: cityObj.name || '',
        countyName: areaObj.name || '',
        streetName: streetObj.name || '',
        communityName: villageObj.name || ''
      },
      defaultObj: {
        provinceObj,
        cityObj,
        areaObj,
        streetObj,
        villageObj
      },
      fullArea: fullAreaName.toString().replace(/,/g, '')
    }
  }
  emit('update:value', areaInfoObj.fullArea)
  areaFullName.value = areaInfoObj.fullArea
  emit('confirm', areaInfoObj)
  showAddressSelector.value = false
}
//下拉选择
const anewSelect = num => {
  console.log(num)
  switch (num) {
    case 0:
      if (props.defaultLimitArea >= 0) {
        return
      }
      showIndex.value = 0
      state.cityObj = {}
      state.areaObj = {}
      state.streetObj = {}
      state.villageObj = {}
      state.cityData = []
      state.areaData = []
      state.streetsData = []
      state.villagesData = []
      handleGetMap({}, 'init')
      break
    case 1:
      if (props.defaultLimitArea >= 1) {
        return
      }
      showIndex.value = 1
      state.streetObj = {}
      state.villageObj = {}
      state.areaObj = {}
      state.areaData = []
      state.streetsData = []
      state.villagesData = []
      // if (!state.areaObj.id) return;

      handleGetMap(state.provinceObj, 'pro')
      break
    case 2:
      if (props.defaultLimitArea.value >= 2) {
        return
      }
      showIndex.value = 2
      state.streetObj = {}
      state.villageObj = {}
      state.streetsData = []
      state.villagesData = []
      // if (!state.streetObj.id) return;
      handleGetMap(state.cityObj, 'city')
      break
    case 3:
      if (props.defaultLimitArea.value >= 3) {
        return
      }
      showIndex.value = 3
      state.villageObj = {}
      state.villagesData = []
      handleGetMap(state.areaObj, 'area')
      break
    case 4:
      if (props.defaultLimitArea.value >= 4) {
        return
      }
      showIndex.value = 4
      // state.streetObj = {}
      // state.streetsData = []
      handleGetMap(state.streetObj, 'street')
      break
    case 5:
      showIndex.value = 5
      state.villagesData = []
      state.villageObj = {}
      // if (!state.villageObj.id) return;
      handleGetMap(state.villageObj, 'area')
      break
  }
}
const handleGetMap = (obj, type) => {
  getAreaByCode(obj, type)
}

const getAreaByCode = (obj, type) => {
  // name选择名称 type类型
  let data = {
    parentArea: 0
  }
  if (type !== 'init') {
    data.parentArea = obj.id
    isLoading.value = true
  }
  let areaCode
  if (obj && obj.id) {
    areaCode = obj.id
  } else {
    areaCode = '000000'
  }
  // 每次请求带上parentArea 即可请求下一级区域数据
  gerAreaByCode(areaCode).then(res => {
    if (res.succeed) {
      // res.data.forEach(element => {
      //   element.disabled = true
      // })
      let arr = ['init', 'pro', 'city', 'area', 'street']
      let _obj = {
        init: 'provinceData',
        pro: 'cityData',
        city: 'areaData',
        area: 'streetsData',
        street: 'villagesData'
      }
      console.log(res.data)
      state[_obj[type]] = res.data
      console.log(state)
      showIndex.value = arr.indexOf(type)
      currentLastLevel.value =
        res.data && res.data.length > 0 ? res.data[0].level : 0
      isLoading.value = false
    } else {
      isLoading.value = false
      showSuccessToast(res.msg)
    }
  })
}
const handleSelectAddress = (type, obj) => {
  console.log(type, obj)
  if (obj.disabled) {
    return
  }
  switch (type) {
    case 0:
      //选择省
      handleGetMap(obj, 'pro')
      state.provinceObj = obj
      showIndex.value = 1
      state.cityData = []
      state.areaData = []
      state.streetsData = []
      state.villagesData = []
      break
    case 1:
      //选择市
      handleGetMap(obj, 'city')
      state.cityObj = obj
      showIndex.value = 2
      state.areaData = []
      state.streetsData = []
      state.villagesData = []

      break
    case 2:
      //选择区
      if (props.selectAreaLevelLimit == 3) {
        state.areaObj = obj
      } else {
        handleGetMap(obj, 'area')
        state.areaObj = obj
        showIndex.value = 3
        state.streetsData = []
        state.villagesData = []
      }
      break
    case 3:
      //选择街道
      if (props.selectAreaLevelLimit == 4) {
        state.streetObj = obj
      } else {
        handleGetMap(obj, 'street')
        showIndex.value = 4
        state.villagesData = []
        state.streetObj = obj
      }
      break
    case 4:
      //选择村、社区
      state.villageObj = obj
      break
    default:
      break
  }
}
</script>

<style lang="less" scoped>
// vant 样式
.van-popup {
  border-radius: 32px 32px 0 0 !important;
}
.page-main {
  z-index: 999;
  background-color: #ffffff;
  border-top: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 16px 16px 0 0;
  height: 98%;
  .main-operate {
    padding: 0 20px;
    height: 80px;
    line-height: 80px;
    display: flex;
    justify-content: space-between;
    .title-txt {
      color: #343434;
      font-size: 30px;
      &:nth-child(2) {
        color: rgb(64, 158, 255);
      }
    }
  }
  .main-select {
    display: flex;
    justify-content: flex-start;
    color: #343434;
    font-size: 26px;
    height: 80px;
    line-height: 80px;
    margin-left: 20px;
    div:nth-child(1) {
      min-width: 80px;
    }
    div:nth-child(2) {
      min-width: 80px;
    }
    div:nth-child(3) {
      min-width: 80px;
    }
    div {
      display: inline-block;
      padding: 0 10px;
      div-align: center;
      overflow: hidden;
      -webkit-line-clamp: 1;
      div-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      div-align: center;
    }
    .select {
      font-size: 26px;
      color: #ff4242;
      position: relative;
      &::after {
        content: '';
        width: 100%;
        height: 4px;
        background: #ff4242;
        position: absolute;
        left: 0;
        bottom: 0;
        border-radius: 6px;
      }
    }
  }
  .main-list {
    position: relative;
    overflow-y: auto;
    color: #343434;
    width: 100%;
    height: calc(100% - 160px);
    overflow: auto;
    .list-box {
      display: flex;
      justify-content: flex-start;
      padding-left: 28px;
      height: 80px;
      font-size: 26px;
      line-height: 80px;
    }
    .list-box:last-child {
      border-bottom: none;
    }
    .active {
      color: #ee0a24;
      position: relative;
      &::after {
        content: '';
        width: 30px;
        height: 30px;
        background: url('../../assets/img/common/selectedIcon.png') no-repeat;
        background-size: 100% 100%;
        background-position: center;
        position: absolute;
        right: 28px;
        top: 50%;
        transform: translateY(-50%);
        color: #ee0a24;
      }
    }
  }
}
.select {
  position: relative;
}
.select::after {
  position: absolute;
  box-sizing: border-box;
  content: ' ';
  pointer-events: none;
  right: 0.42667rem;
  bottom: 0;
  left: 0.42667rem;
  border-bottom: 0.02667rem solid #ebedf0;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
}
</style>
